<script setup>
import { ref, onMounted, reactive } from 'vue';
import { 
  Search, 
  Delete, 
  Edit, 
  View, 
  Hide, 
  Check,
  Close,
  Refresh
} from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import request, { SERVER_BASE_URL } from '@/utils/request.js';

// 文章数据
const articleList = ref([]);
const total = ref(0);
const loading = ref(false);
const articleDetailVisible = ref(false);
const currentArticle = ref({});

// 分页和筛选参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 9,
  status: '',
  userId: ''
});

// 状态选项
const statusOptions = [
  { value: '', label: '全部' },
  { value: 'PUBLISHED', label: '已发布' },
  { value: 'DRAFT', label: '草稿' },
  { value: 'HIDDEN', label: '已隐藏' }
];

// 状态显示
const statusMap = {
  'PUBLISHED': { label: '已发布', type: 'success' },
  'DRAFT': { label: '草稿', type: 'info' },
  'HIDDEN': { label: '已隐藏', type: 'warning' }
};

// 加载文章列表
const getArticles = async () => {
  loading.value = true;
  try {
    const { data: res } = await request.get('/article/list', {
      params: {
        pageNum: queryParams.pageNum,
        pageSize: queryParams.pageSize,
        status: queryParams.status,
        userId: queryParams.userId || undefined
      }
    });
    console.log(res)

    articleList.value = res.list || [];
    total.value = res.total || 0;
  } catch (error) {
    console.error('获取文章列表失败', error);
    ElMessage.error('获取文章列表失败');
  } finally {
    loading.value = false;
  }
};

// 查看文章详情
const viewArticleDetail = async (id) => {
  try {
    const { data } = await request.get(`/article/detail/${id}`);
    currentArticle.value = data || {};
    articleDetailVisible.value = true;
  } catch (error) {
    console.error('获取文章详情失败', error);
    ElMessage.error('获取文章详情失败');
  }
};

// 查看文章页面
const openArticlePage = (id) => {
  window.open(`/article/${id}`, '_blank');
};

// 处理文章状态变更
const changeArticleStatus = async (article, newStatus) => {
  try {
    await request.put('/article/update', {
      id: article.id,
      status: newStatus
    });
    
    ElMessage.success(`文章状态已更新为${statusMap[newStatus].label}`);
    // 更新本地数据
    article.status = newStatus;
  } catch (error) {
    console.error('更新文章状态失败', error);
    ElMessage.error('更新文章状态失败');
  }
};

// 删除文章
const deleteArticle = (id) => {
  ElMessageBox.confirm('确定要删除这篇文章吗？此操作不可恢复！', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await request.delete(`/article/delete/${id}`);
      ElMessage.success('文章已删除');
      getArticles(); // 刷新列表
    } catch (error) {
      console.error('删除文章失败', error);
      ElMessage.error('删除文章失败');
    }
  }).catch(() => {
    // 用户取消删除
  });
};

// 重置查询条件
const resetQuery = () => {
  queryParams.status = '';
  queryParams.userId = '';
  queryParams.pageNum = 1;
  getArticles();
};

// 处理分页变化
const handleSizeChange = (size) => {
  queryParams.pageSize = size;
  getArticles();
};

const handleCurrentChange = (current) => {
  queryParams.pageNum = current;
  getArticles();
};

// 处理图片URL
const getImgUrl = (url) => {
  if (!url) return '';

  // 确保有服务器地址前缀
  const serverBaseUrl = SERVER_BASE_URL;
  let fullUrl = url;

  if (url.startsWith('/uploads/')) {
    fullUrl = serverBaseUrl + url;
  } else if(url.startsWith('uploads/')){
    fullUrl = serverBaseUrl + '/' + url;
  }

  return fullUrl;
};

// 获取文章第一张预览图
const getFirstImage = (mediaList) => {
  if (!mediaList || !mediaList.length) return null;
  
  const images = mediaList.filter(media => media.mediaType === 'IMAGE');
  return images.length > 0 ? images[0].mediaUrl : null;
};

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return '-';
  const date = new Date(dateString);
  return date.toLocaleString('zh-CN', { 
    year: 'numeric', 
    month: '2-digit', 
    day: '2-digit',
    hour: '2-digit', 
    minute: '2-digit'
  });
};

// 初始化
onMounted(() => {
  getArticles();
});
</script>

<template>
  <div class="article-management">
    <el-card class="article-card">
      <template #header>
        <div class="card-header">
          <span class="header-title">文章管理</span>
        </div>
      </template>

      <!-- 搜索和筛选 -->
      <el-form :inline="true" :model="queryParams" class="search-form">
        <el-form-item label="文章状态">
          <el-select v-model="queryParams.status" placeholder="请选择文章状态" clearable style="width: 140px;">
            <el-option
              v-for="item in statusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="用户ID">
          <el-input v-model="queryParams.userId" placeholder="请输入用户ID" clearable style="width: 160px;" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="getArticles">搜索</el-button>
          <el-button :icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 文章列表 -->
      <el-table
        v-loading="loading"
        :data="articleList"
        border
        style="width: 100%"
      >
        <el-table-column label="ID" prop="id" width="80" />
        <el-table-column label="用户昵称" width="180">
          <template #default="{ row }">
            <div>
<!--              <div>ID: {{ row.author.id }}</div>-->
              <div>{{ row.author.nickname || '未知' }}</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="内容" min-width="250">
          <template #default="{ row }">
            <div class="article-content-preview">
              <div class="content-text">{{ row.content }}</div>
              <div v-if="getFirstImage(row.mediaList)" class="content-image">
                <el-image 
                  :src="getImgUrl(getFirstImage(row.mediaList))" 
                  fit="cover"
                  :preview-src-list="row.mediaList && row.mediaList.filter(m => m.mediaType === 'IMAGE').map(m => getImgUrl(m.mediaUrl))"
                  preview-teleported
                />
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="媒体数量" prop="mediaCount" width="90" align="center" />
        <el-table-column label="点赞数" prop="likes" width="80" align="center" />
        <el-table-column label="评论数" prop="commentCount" width="80" align="center" />
        <el-table-column label="状态" prop="status" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="statusMap[row.status]?.type">
              {{ statusMap[row.status]?.label }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="发布时间" width="160">
          <template #default="{ row }">
            {{ formatDate(row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="220" fixed="right">
          <template #default="{ row }">
            <el-button
              type="primary"
              size="small"
              text
              @click="viewArticleDetail(row.id)"
            >
              详情
            </el-button>
            <el-dropdown trigger="click" @command="(command) => changeArticleStatus(row, command)">
              <el-button
                type="primary"
                size="small"
                text
              >
                修改状态
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item
                    v-for="option in statusOptions.filter(o => o.value && o.value !== row.status)"
                    :key="option.value"
                    :command="option.value"
                  >
                    {{ option.label }}
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
            <el-button
              type="danger"
              size="small"
              text
              @click="deleteArticle(row.id)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="queryParams.pageNum"
          v-model:page-size="queryParams.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 文章详情对话框 -->
    <el-dialog
      v-model="articleDetailVisible"
      title="文章详情"
      width="700px"
    >
      <el-descriptions title="基本信息" :column="2" border>
        <el-descriptions-item label="文章ID">{{ currentArticle.id }}</el-descriptions-item>
        <el-descriptions-item label="发布时间">{{ formatDate(currentArticle.createTime) }}</el-descriptions-item>
        <el-descriptions-item label="用户ID">{{ currentArticle.author.id }}</el-descriptions-item>
        <el-descriptions-item label="用户昵称">{{ currentArticle.author.nickname || '未知' }}</el-descriptions-item>
        <el-descriptions-item label="点赞数">{{ currentArticle.likes }}</el-descriptions-item>
        <el-descriptions-item label="评论数">{{ currentArticle.commentCount }}</el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="statusMap[currentArticle.status]?.type">
            {{ statusMap[currentArticle.status]?.label }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="更新时间">{{ formatDate(currentArticle.updateTime) }}</el-descriptions-item>
      </el-descriptions>

      <el-divider content-position="center">内容</el-divider>
      
      <div class="article-content">
        {{ currentArticle.content }}
      </div>
      
      <el-divider v-if="currentArticle.mediaList && currentArticle.mediaList.length > 0" content-position="center">媒体文件</el-divider>
      
      <div v-if="currentArticle.mediaList && currentArticle.mediaList.length > 0" class="media-preview">
        <div 
          v-for="media in currentArticle.mediaList" 
          :key="media.id"
          class="media-item"
        >
          <el-image 
            v-if="media.mediaType === 'IMAGE'"
            :src="getImgUrl(media.mediaUrl)" 
            fit="cover"
            :preview-src-list="currentArticle.mediaList.filter(m => m.mediaType === 'IMAGE').map(m => getImgUrl(m.mediaUrl))"
            preview-teleported
          />
          <video 
            v-else-if="media.mediaType === 'VIDEO'" 
            controls
            class="video-preview"
          >
            <source :src="getImgUrl(media.mediaUrl)" type="video/mp4">
          </video>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<style scoped>
.article-management {
  padding: 0;
}

.article-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-title {
  font-size: 18px;
  font-weight: bold;
}

.search-form {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.article-content-preview {
  display: flex;
  gap: 10px;
  align-items: center;
}

.content-text {
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  max-height: 40px;
}

.content-image {
  width: 50px;
  height: 50px;
  flex-shrink: 0;
  overflow: hidden;
  border-radius: 4px;
}

.content-image .el-image {
  width: 100%;
  height: 100%;
}

.article-content {
  padding: 10px;
  background-color: #f8f8f8;
  border-radius: 4px;
  white-space: pre-wrap;
  word-break: break-word;
  max-height: 200px;
  overflow-y: auto;
}

.media-preview {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin-top: 10px;
}

.media-item {
  width: 120px;
  height: 120px;
  border-radius: 4px;
  overflow: hidden;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f0f0f0;
  position: relative;
}

.media-item .el-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.video-preview {
  width: 100%;
  height: 100%;
  object-fit: cover;
}
</style>